import React, { useState } from 'react';
import styled from 'styled-components';
import { motion } from 'framer-motion';
import { FaSave, FaShareAlt, FaStar, FaVenus, FaMars } from 'react-icons/fa';
import { colors, spacing, typography } from '../styles/variables';
import { Card, Title, Paragraph, Button, Input, Flex } from '../styles/components';

// 定义五行颜色
const WUXING_COLORS = {
  木: '#22c55e', // 绿色
  火: '#ef4444', // 红色
  土: '#ca8a04', // 黄色
  金: '#a1a1aa', // 灰色
  水: '#3b82f6'  // 蓝色
};

const BaziHeader = styled.div`
  text-align: center;
  padding: ${spacing.xl} 0;
  margin-bottom: ${spacing.xl};
`;

const FormCard = styled(Card)`
  max-width: 600px;
  margin: 0 auto;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 15px;
  box-shadow: 0 20px 40px rgba(0,0,0,0.1);
  backdrop-filter: blur(10px);
`;

const FormGroup = styled.div`
  margin-bottom: ${spacing.lg};
`;

const Label = styled.label`
  display: block;
  color: ${colors.textPrimary};
  margin-bottom: ${spacing.sm};
  font-weight: ${typography.fontWeight.medium};
`;

const GenderSelector = styled.div`
  display: flex;
  gap: ${spacing.md};
  margin-top: ${spacing.sm};
`;

const GenderButton = styled(Button)`
  flex: 1;
  background: ${props => props.selected ? colors.gradientGold : colors.backgroundSecondary};
  color: ${props => props.selected ? colors.background : colors.textPrimary};
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
`;

const ResultSection = styled.div`
  margin-top: ${spacing.xxl};
  background: rgba(255, 255, 255, 0.95);
  padding: 2rem;
  border-radius: 15px;
  box-shadow: 0 20px 40px rgba(0,0,0,0.1);
  margin-top: 2rem;
  backdrop-filter: blur(10px);
`;

// 柱子容器
const PillarsContainer = styled.div`
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 1rem;
  margin-bottom: 2rem;
  
  @media (max-width: 768px) {
    grid-template-columns: repeat(2, 1fr);
  }
`;

// 柱子
const Pillar = styled(motion.div)`
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border: 2px solid #0ea5e9;
  border-radius: 12px;
  padding: 1.5rem;
  text-align: center;
  box-shadow: 0 4px 15px rgba(14, 165, 233, 0.2);
`;

// 柱子标题
const PillarTitle = styled.h4`
  color: #0369a1;
  margin: 0 0 1rem 0;
  font-size: 1.1rem;
  font-weight: 600;
`;

// 天干
const TianGan = styled.div`
  font-size: 2rem;
  font-weight: bold;
  color: #0891b2;
  margin-bottom: 0.5rem;
`;

// 地支
const DiZhi = styled.div`
  font-size: 1.5rem;
  color: #0e7490;
`;

// 五行属性容器
const FiveElementsContainer = styled.div`
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 1rem;
  margin: 2rem 0;
  
  @media (max-width: 768px) {
    grid-template-columns: repeat(2, 1fr);
  }
`;

// 五行属性项
const FiveElementItem = styled(motion.div)`
  background: ${props => `linear-gradient(135deg, ${WUXING_COLORS[props.element]} 0%, ${WUXING_COLORS[props.element]}dd 100%)`};
  color: white;
  padding: 1rem;
  border-radius: 12px;
  text-align: center;
  box-shadow: 0 4px 15px rgba(0,0,0,0.2);
`;

// 五行名称
const ElementName = styled.div`
  font-size: 1.1rem;
  font-weight: 600;
  margin-bottom: 0.5rem;
`;

// 五行数值
const ElementValue = styled.div`
  font-size: 1.5rem;
  font-weight: bold;
`;

// 分析卡片容器
const AnalysisCardsContainer = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 1.5rem;
  margin-top: 2rem;
`;

// 分析卡片
const AnalysisCard = styled(motion.div)`
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border: 2px solid #94a3b8;
  border-radius: 12px;
  padding: 1.5rem;
  box-shadow: 0 4px 15px rgba(148, 163, 184, 0.2);
`;

// 分析标题
const AnalysisTitle = styled.h4`
  color: #334155;
  margin: 0 0 1rem 0;
  font-size: 1.2rem;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 0.5rem;
`;

// 分析内容
const AnalysisContent = styled.p`
  color: #64748b;
  line-height: 1.6;
  margin: 0;
`;

// 操作按钮容器
const ActionButtons = styled.div`
  display: flex;
  gap: 1rem;
  margin-top: 1.5rem;
  justify-content: center;
`;

// 操作按钮
const ActionButton = styled(motion.button)`
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1.5rem;
  background: ${props => props.primary ? 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' : 'white'};
  color: ${props => props.primary ? 'white' : '#374151'};
  border: 2px solid ${props => props.primary ? 'transparent' : '#d1d5db'};
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  box-shadow: 0 4px 15px rgba(0,0,0,0.1);
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(0,0,0,0.15);
  }
`;

function BaziCalculator() {
  const [formData, setFormData] = useState({
    birthDate: '',
    birthTime: '',
    timezone: '+08:00',
    gender: 'male'
  });
  
  const [result, setResult] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleGenderSelect = (gender) => {
    setFormData(prev => ({
      ...prev,
      gender
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    // 验证必填字段
    if (!formData.birthDate || !formData.birthTime || !formData.gender) {
      setError('请填写所有必填字段');
      return;
    }
    
    setLoading(true);
    setError('');
    
    try {
      // 构造正确的API路径和参数
      const birthDateTime = new Date(`${formData.birthDate}T${formData.birthTime}`);
      const timezoneOffset = birthDateTime.getTimezoneOffset() / -60;
      
      // 调用真实的API
      const response = await fetch('/api/divination/bazi/calculate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          birthDate: formData.birthDate,
          birthTime: formData.birthTime,
          timezone: timezoneOffset,
          gender: formData.gender
        })
      });
      
      // 检查响应是否为JSON格式
      const contentType = response.headers.get('content-type');
      if (!contentType || !contentType.includes('application/json')) {
        const text = await response.text();
        throw new Error(`服务器响应格式错误: ${text.substring(0, 100)}...`);
      }
      
      const data = await response.json();
      
      if (data.success) {
        // 获取分析结果
        const analysisResponse = await fetch('/api/divination/bazi/analyze', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            bazi: data.data.bazi
          })
        });
        
        // 检查分析响应是否为JSON格式
        const analysisContentType = analysisResponse.headers.get('content-type');
        if (!analysisContentType || !analysisContentType.includes('application/json')) {
          const text = await analysisResponse.text();
          throw new Error(`服务器分析响应格式错误: ${text.substring(0, 100)}...`);
        }
        
        const analysisData = await analysisResponse.json();
        
        if (analysisData.success) {
          setResult({
            bazi: data.data.bazi,
            analysis: analysisData.data.analysis
          });
        } else {
          throw new Error(analysisData.message || '分析失败');
        }
      } else {
        throw new Error(data.message || '计算失败');
      }
    } catch (err) {
      setError(err.message || '计算失败，请稍后重试');
      console.error('八字测算错误:', err);
    } finally {
      setLoading(false);
    }
  };

  // 保存结果
  const handleSave = () => {
    alert('结果已保存！');
  };
  
  // 分享结果
  const handleShare = () => {
    alert('分享功能待实现');
  };

  return (
    <>
      <BaziHeader>
        <Title>八字测算</Title>
        <Paragraph center>输入您的出生信息，获取详细的八字命理分析</Paragraph>
      </BaziHeader>

      <FormCard>
        <form onSubmit={handleSubmit}>
          <FormGroup>
            <Label>出生日期 *</Label>
            <Input
              type="date"
              name="birthDate"
              value={formData.birthDate}
              onChange={handleChange}
              required
            />
          </FormGroup>
          
          <FormGroup>
            <Label>出生时间 *</Label>
            <Input
              type="time"
              name="birthTime"
              value={formData.birthTime}
              onChange={handleChange}
              required
            />
          </FormGroup>
          
          <FormGroup>
            <Label>时区</Label>
            <Input
              type="text"
              name="timezone"
              value={formData.timezone}
              onChange={handleChange}
              placeholder="例如: +08:00"
            />
          </FormGroup>
          
          <FormGroup>
            <Label>性别 *</Label>
            <GenderSelector>
              <GenderButton 
                type="button" 
                selected={formData.gender === 'male'}
                onClick={() => handleGenderSelect('male')}
              >
                <FaMars /> 男
              </GenderButton>
              <GenderButton 
                type="button" 
                selected={formData.gender === 'female'}
                onClick={() => handleGenderSelect('female')}
              >
                <FaVenus /> 女
              </GenderButton>
            </GenderSelector>
          </FormGroup>
          
          {error && (
            <div style={{ color: '#ef4444', marginBottom: '1rem' }}>
              {error}
            </div>
          )}
          
          <Flex justify="center">
            <Button variant="primary" type="submit" disabled={loading}>
              {loading ? '计算中...' : '开始测算'}
            </Button>
          </Flex>
        </form>
      </FormCard>

      {result && (
        <ResultSection>
          <Title size="md" style={{ textAlign: 'center', marginBottom: '2rem' }}>您的八字命盘</Title>
          
          <PillarsContainer>
            <Pillar
              initial={{ opacity: 0, scale: 0.8 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ delay: 0.3 }}
            >
              <PillarTitle>年柱</PillarTitle>
              <TianGan>{result.bazi.year.tiangan}</TianGan>
              <DiZhi>{result.bazi.year.dizhi}</DiZhi>
            </Pillar>
            
            <Pillar
              initial={{ opacity: 0, scale: 0.8 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ delay: 0.4 }}
            >
              <PillarTitle>月柱</PillarTitle>
              <TianGan>{result.bazi.month.tiangan}</TianGan>
              <DiZhi>{result.bazi.month.dizhi}</DiZhi>
            </Pillar>
            
            <Pillar
              initial={{ opacity: 0, scale: 0.8 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ delay: 0.5 }}
            >
              <PillarTitle>日柱</PillarTitle>
              <TianGan>{result.bazi.day.tiangan}</TianGan>
              <DiZhi>{result.bazi.day.dizhi}</DiZhi>
            </Pillar>
            
            <Pillar
              initial={{ opacity: 0, scale: 0.8 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ delay: 0.6 }}
            >
              <PillarTitle>时柱</PillarTitle>
              <TianGan>{result.bazi.hour.tiangan}</TianGan>
              <DiZhi>{result.bazi.hour.dizhi}</DiZhi>
            </Pillar>
          </PillarsContainer>
          
          <h3 style={{ textAlign: 'center', color: '#374151', marginBottom: '1rem' }}>
            五行属性
          </h3>
          
          <FiveElementsContainer>
            {Object.entries(result.analysis.fiveElements).map(([element, value], index) => (
              <FiveElementItem
                key={element}
                element={element}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.7 + index * 0.1 }}
              >
                <ElementName>{element}</ElementName>
                <ElementValue>{Math.round(value * 100)}</ElementValue>
              </FiveElementItem>
            ))}
          </FiveElementsContainer>
          
          <AnalysisCardsContainer>
            <AnalysisCard
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 1.2 }}
            >
              <AnalysisTitle>
                <FaStar /> 性格分析
              </AnalysisTitle>
              <AnalysisContent>
                {result.analysis.personality}
              </AnalysisContent>
            </AnalysisCard>
            
            <AnalysisCard
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 1.3 }}
            >
              <AnalysisTitle>
                <FaStar /> 事业分析
              </AnalysisTitle>
              <AnalysisContent>
                {result.analysis.career}
              </AnalysisContent>
            </AnalysisCard>
            
            <AnalysisCard
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 1.4 }}
            >
              <AnalysisTitle>
                <FaStar /> 感情分析
              </AnalysisTitle>
              <AnalysisContent>
                {result.analysis.relationship}
              </AnalysisContent>
            </AnalysisCard>
            
            <AnalysisCard
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 1.5 }}
            >
              <AnalysisTitle>
                <FaStar /> 健康分析
              </AnalysisTitle>
              <AnalysisContent>
                {result.analysis.health}
              </AnalysisContent>
            </AnalysisCard>
          </AnalysisCardsContainer>
          
          <ActionButtons>
            <ActionButton
              primary
              onClick={handleSave}
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
            >
              <FaSave /> 保存结果
            </ActionButton>
            <ActionButton
              onClick={handleShare}
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
            >
              <FaShareAlt /> 分享
            </ActionButton>
          </ActionButtons>
        </ResultSection>
      )}
    </>
  );
}

export default BaziCalculator;